package vip.liux.contracts.infrastructure.messaging.handlers;

import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import vip.liux.contracts.infrastructure.messaging.MessageConst;
import vip.liux.contracts.shared.enums.messing.ChannelType;
import vip.liux.sms.ISmsSender;
import vip.liux.sms.NullSmsSender;

public class SmsMessageHandler extends AbstractMessageHandler {

    @Setter
    private ISmsSender smsSender = new NullSmsSender();

    public SmsMessageHandler() {
    }

    public SmsMessageHandler(ISmsSender smsSender) {
        this.smsSender = smsSender;
    }

    /**
     * 处理传入的消息并发送短信
     *
     * @param message 要处理的消息
     * @throws MessagingException 如果处理消息失败
     */
    @Override
    public void handleMessage(@NotNull Message<?> message) throws MessagingException {
        try {
            // 从消息中提取短信内容和目标号码
            String phoneNumber = (String) message.getHeaders().get(MessageConst.TO);
            String content = (String) message.getPayload();

            if (StringUtils.isBlank(phoneNumber)) {
                throw new MessagingException("Phone number is blank");
            }

            // 调用 ISmsSender 发送短信
            smsSender.send(phoneNumber, content);
        } catch (Exception e) {
            // 捕获异常并抛出 MessagingException
            throw new MessagingException("Failed to send SMS", e);
        }
    }

    @Override
    public boolean supports(ChannelType channelType) {
        return ChannelType.SMS.equals(channelType);
    }
}